package network

import (
	"fmt"
	"net"
	"time"
)

func StartTcpConn(addr string) *TCPConnect {
	conn := &TCPConnect{
		TCPSocket: TCPSocket{
			tCPConn: nil,
			guid:    genGuid(),
			//readChan:  m.readChan,
			writeChan: make(chan *SendPacket, ID_CONNECT_WRITE_CHAN_LENGTH),
		},
		addr: addr,
	}

	socketMap.Store(conn.GetGuid(), conn)
	conn.run()
	return conn
}

func (m *TCPConnect) run() {
	m.syncClose.Add(2)
	go m.monitor()
	go m.connect()
}

func (m *TCPConnect) connect() {
	addr, err := net.ResolveTCPAddr("tcp", m.addr)
	if err != nil {
		fmt.Printf("TCPConnect:%v ResolveTCPAddr error %v\n", m.addr, err)
		return
	}

	for {
		tcpConn, err := net.DialTCP("tcp", nil, addr)
		if err != nil {
			fmt.Printf("TCPConnect:%v connection fail %v\n", m.addr, err)
			time.Sleep(time.Second * time.Duration(ID_TCP_RECONNECT_TIME))
		} else {
			fmt.Printf("TCPConnect:%v connection success\n", m.addr)
			m.tCPConn = tcpConn
			break
		}
	}

	go m.read()
	go m.write()
	m.addPack(ID_MSG_TYPE_CONN_NEW_CONNECTION, nil)
}

func (m *TCPConnect) monitor() {
	m.syncClose.Wait()
	m.addPack(ID_MSG_TYPE_CONN_DISCONNECTION, nil)
	fmt.Printf("TCPConnect:%v monitor end\n", m.GetGuid())
	m.run()
}
